package data

import (
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"os"
)

type DDD struct {
	Recipient   string `json:"recipient"`
	Information string `json:"information"`
}

type Delivery struct {
	AuthCode string `json:"authCode"`
	State    string `json:"state"`
	Sender   string `json:"sender"`
	Data     DDD    `json:"data"`
}

var Conns = make(map[string]net.Conn)

func TcpConnect() {
	// 启动服务器，监听本地的8080端口
	ln, err := net.Listen("tcp", "0.0.0.0:8081")
	if err != nil {
		fmt.Println("Error starting server:", err)
		os.Exit(1)
	}
	defer ln.Close()

	fmt.Println("成功连接tcp 8081...")

	for {
		// 接受一个客户端连接
		conn, err := ln.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}
		fmt.Println("Client connected:", conn.RemoteAddr())

		// 处理客户端连接
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()

	// 读取客户端发送的数据
	reader := bufio.NewReader(conn)
	for {
		var newD Delivery
		err := json.NewDecoder(reader).Decode(&newD)
		if err != nil || newD.AuthCode != "zhangjunjieiizhangbaofan" {
			fmt.Println("程序退出:", err)
			return
		}

		if newD.State == "weihu" {
			Conns[newD.Sender] = conn
			fmt.Println(Conns)
		} else {
			myconn, ok := Conns[newD.Data.Recipient]
			if ok {
				// 回传消息给客户端
				err = json.NewEncoder(myconn).Encode(newD)
				if err != nil {
					fmt.Println("Error writing to client:", err)
					return
				}
			} else {
				fmt.Println("未知请求,来自于：", conn.RemoteAddr())
			}
		}
	}
}
